<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Course\Lesson;
use App\Models\Course;
use App\Models\CourseLesson;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Storage;

class CourseController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Course';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Course());
        $grid->column('id', __('Id'));
        $grid->column('name', __('课程名称'));
        $grid->column('type', __('类型'))->display(function ($type)  {
            return Course::$typeMap[$type];
        });
        $grid->column('thumb', __('缩略图'))->display(function ($thumb) {
            if($thumb) {
                return "<img src='".Storage::url('')."{$thumb}' width='50' height='50'>";
            }
        });
        $grid->column('is_recommend', __('是否推荐'));

        $grid->column('created_at', __('Created at'));
        $grid->actions(function ($actions) {
            $actions->add(new Lesson);
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Course::findOrFail($id));
        $show->field('id', __('Id'));
        $show->field('name', __('课程名称'));
        $show->field('type', __('类型'));
        $show->field('thumb', __('缩略图'));
        $show->field('is_recommend', __('是否推荐'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('description', __('description'));
        $show->field('content', __('content'));
        $show->field('sort', __('sort'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Course());
        $form->text('name', __('课程名称'));
        $form->select('type', __('类型'))->options(Course::$typeMap);
        $form->image('thumb', __('缩略图'));
        $form->radio('is_recommend', __('是否推荐'))->options([1 => '是', 0 => '否']);
        $form->textarea('description', __('课程简介'));
        $form->textarea('content');
        $form->hasMany('lesson', '课程', function (Form\NestedForm $form) {
            $form->text('title', __('课时标题'));
            $form->select('type', __('课时类型'))->options(CourseLesson::$typeMap);
            $form->textarea('content', __('课时内容'));
            $form->file('lesson_file', __('课时文件'));
            $form->multipleFile('extends', __('扩展文件'));
            $form->number('sort', __('排序'));
            $form->radio('status', __('状态'))->options(CourseLesson::$statusMap);
         });
         
        return $form;
    }
}
